import store from '@/store'
import { mapGetters } from 'vuex'
import { isPc, getDeviceType, isJSON, isIos } from '@/utils'
import { handleHotspot } from '@/utils/hotspot'
import { hasMiniMap } from '@/utils/menu'
import { handleEffect, visibleGyro, visibleGyroOn } from '@/utils/krpano'
import { pauseAllAudio, replaySceneOrBgMusic } from '@/utils/audio'
import $AUTH from '@/utils/auth'
import $API from '@/api/services'

const install = function (Vue) {
  const krviewPlugin = new Vue({
    data () {
      return {
        _krpano: null,
        hotspotData: null, // 当前场景热点数据
        hotspotCommentsData: null, // 当前场景评论数据
        hotspotsCache: {}, // 热点缓存对象
        isFristCallViewType: true,//是否是第一次进入场景
        lastScene: null, // 上一个场景
        tip: null
      }
    },
    computed: {
      ...mapGetters([
        'panoInfo',
        'hotspots',
        'userInfo'
      ]),
      getPanoInfo () {
        if (store.getters.panoInfo) {
          return store.getters.panoInfo
        }
      },
      getTemp12 () {
        if (store.getters.panoInfo && store.getters.panoInfo.templatetype == 12) {
          return true
        }
      }
    },
    created () {
      const ComponentConstructor = Vue.extend(require('@/assets/mark.vue').default)
      this.tip = new ComponentConstructor().$mount()
    },
    methods: {
      // 控制内嵌视频播放和暂停
      controlsAllVideoin (val = false) {
        // val=true播放,false暂停
        // console.log(val)
        // 获取当前场景id
        let id = this.getSceneId()
        // console.log(id)
        // console.log(this.hotspotsCache)
        if (this.hotspotsCache && this.hotspotsCache[id] && this.hotspotsCache[id].hotspotlist && this.hotspotsCache[id].hotspotlist.length > 0) {
          let list = this.hotspotsCache[id].hotspotlist
          list.map(item => {
            // 只处理内嵌视频
            if (item.type_id == 9 && item.diy_id == 0 && !item.pointlist) {
              let krObj = this.getSceneData(`hotspot[hotspot_${item.hot_id}]`)
              console.log(krObj)
              if (val) {
                if (krObj && krObj.videoDOM && krObj.videoDOM.paused) {
                  krObj.togglepause()
                }
              } else {
                if (krObj && krObj.videoDOM && !krObj.videoDOM.paused) {
                  krObj.togglepause()
                }
              }
            }
          })
        }
      },
      initKrpno (options) {
        this._krpano = options
        this.loadHotpoints()
      },
      loadHotpoints () {
        this.sceneList = this.getScene()
        let timer = setTimeout(() => {
          if (this.sceneList && this.sceneList.length > 0) {
            clearTimeout(timer)

            let id = this.getSceneId()
            // 获取场景热点
            this.initHotpoints(id)

          } else {
            this.loadHotpoints()
          }
        }, 5)
      },
      initHotpoints (sceneId) {
        if (this.getPanoInfo && JSON.stringify(this.getPanoInfo) !== '{}') {
          // isstartscene=1小行星开场效果2无效果3小行星开场旋转效果
          let count = 12000
          if (this.getPanoInfo.isstartscene === 3) {

            if (this.getPanoInfo && this.getPanoInfo.loadinfo && this.getPanoInfo.loadinfo.showtime >= 0) {
              count = Number(this.getPanoInfo.loadinfo.showtime) + 7000
            }
            count = count < 12000 ? 12000 : count

            setTimeout(() => {
              store.dispatch('fetchSceneHotspots', sceneId)
            }, count)
          } else {
            if (this.getPanoInfo.isloading === 1 && this.getPanoInfo.load_type === 0) {
              setTimeout(() => {
                store.dispatch('fetchSceneHotspots', sceneId)
              }, ((this.getPanoInfo.loadinfo && this.getPanoInfo.loadinfo.showtime) ? this.getPanoInfo.loadinfo.showtime : 3000))
            } else {
              store.dispatch('fetchSceneHotspots', sceneId)
            }
          }

          // 补地图片
          this.setBottomPic()

          // 初始化视角
          this.switchPerspective()


          setTimeout(() => {
            // 初始化陀螺仪状态
            !isPc() && visibleGyro() && visibleGyroOn() && this.toggleGyro()

            // 加载小地图
            const miniMap = hasMiniMap(sceneId)
            if (miniMap) {
              $VM.$vgo.emit('show:minimap-icon', miniMap)
            }
          }, (this.getPanoInfo.isstartscene === 3) ? count : 5000)

          setTimeout(() => {
            // 自动旋转
            this.autoTurn()
          }, 2000)
        }
      },
      getHotpoints (sceneId) {
        store.dispatch('fetchSceneHotspots', sceneId)

        // 补地图片
        this.setBottomPic()
      },
      loadSceneHotpoints (id) {
        // 视角切换
        this.switchPerspective()
        // 加载热点
        this.getHotpoints(id)
      },
      // 删除热点
      removePoint () {
        this.callScene("removehotspot(get(tempname))")
      },
      // 获取数据
      getSceneData (str) {
        if (this._krpano) {
          return this._krpano.get(str)
        }
      },
      // 获取当前场景名称
      getSceneName () {
        return this.getSceneData("scene[get(xml.scene)].name")
      },
      // 获取场景ID
      getSceneId () {
        if (this.getSceneData("scene[get(xml.scene)].name")) {
          return this.getSceneData("scene[get(xml.scene)].name").split('_')[1]
        }
      },
      // 加载切换效果
      loadScene (id, effect) {
        // 过度效果
        this.callScene("loadscene(scene_" + id + ", null, MERGE, " + effect + ")")
        // 加载热点
        this.loadSceneHotpoints(id)
      },
      moveViewCenter (atv, ath) {
        this.callScene(
          `lookto(${ath},${atv},get(view.fov),tween(easeInOutQuad,0.5),true,true));)`
        )
      },
      // 场景切换效果
      switchEffect (sceneId) {
        if (this.lastScene === sceneId) return

        let time = 1000
        let effectId = store.getters.panoInfo.effecttype
        let effectType = handleEffect(effectId)
        // 如果是缓存效果，effectType为null
        if (effectType) {
          this.callScene("loadscene(scene_" + sceneId + ", js(sceneLoaded()), MERGE, " + effectType + ")")
        } else {
          time = 2000
          this.callScene("transition(scene_" + sceneId + ", get(tempname))")
        }
        this.lastScene = sceneId
        setTimeout(() => {
          // 某些场景切换会出现旋转角度
          // this.loadSceneHotpoints(sceneId)
          // 加载热点
          this.getHotpoints(sceneId)
        }, time)

        // 场景切换时刷新微信分享的内容
        // console.log($globalconfig.MODULES.IS_SHARESCENE_ICON_OPEN)
        if (!isPc()) {
          if ($globalconfig.MODULES.IS_SHARESCENE_ICON_OPEN) {
            if (store.getters.panoInfo && store.getters.panoInfo.group_scene_list) {
              let sceneList = store.getters.panoInfo.group_scene_list
              for (let i in sceneList) {
                for (let j in sceneList[i].scenelist) {
                  if (sceneList[i].scenelist[j].scene_id == sceneId) {
                    // console.log(sceneList[i].scenelist[j].full_thumb_url)
                    store.dispatch('updateWxShareContents', sceneList[i].scenelist[j].full_thumb_url)
                  }
                }
              }
            }
          }
        }

        // 地址栏变更记录，以便客户转发当前地址时能直接进入到转发的这个场景
        if (store.getters.panoInfo.templatetype == 12 && !$VM.$route.query.scene_id) {
          // 景点模板处理
          console.log('111-------------')
          $VM.$router.push({
            name: $VM.$route.name,
            query: Object.assign({}, $VM.$route.query, { scene_id: sceneId, scenic: 1 }),
            params: $VM.$route.params
          })
        } else if (store.getters.panoInfo.templatetype == 11 && location.href.indexOf('scene_id') === -1) {
          // 航拍模板处理
          console.log('222-----------------')
          $VM.$router.push({
            name: $VM.$route.name,
            query: Object.assign({}, $VM.$route.query, { scene_id: sceneId, aerial: 1 }),
            params: $VM.$route.params
          })
        } else {
          console.log('333-------------------')
          $VM.$router.replace({
            name: $VM.$route.name,
            query: Object.assign({}, $VM.$route.query, { scene_id: sceneId }),
            params: $VM.$route.params
          })
        }

        // 景点模板，切换场景获取当前场景的周边场景数据12
        if (store.getters.panoInfo && store.getters.panoInfo.templatetype == 12) {
          // group_scene_list getSceneInfoAct scene_spots_list scenelist
          let groupList = store.getters.panoInfo.group_scene_list
          let sceneScenicInfo = null
          if (groupList && groupList.length > 0) {
            groupList.map(item => {
              if (item.scenelist && item.scenelist.length > 0) {
                item.scenelist.map(sce => {
                  if (sce.scene_id == sceneId) {
                    sceneScenicInfo = sce
                  }
                })
              }
            })
          }
          // console.log(sceneScenicInfo)
          store.dispatch('getSceneInfoAct', sceneScenicInfo)
        }

      },
      // 隐藏评论
      hideComments () {
        if (this.hotspotCommentsData.length) {
          this.hotspotCommentsData.map(item => {
            this.callScene('removehotspot(comment_' + item.comment_id + ')')
          })
        }
      },
      // 显示评论
      showComments () {
        this.addHotspotComments(this.hotspotCommentsData)
      },
      // 加载热点
      loadHotspots (obj) {
        // ishideall=1时隐藏热点
        if (window.location.hash.indexOf('ishideall=1') !== -1) {
          return console.log('页面在iframe中隐藏热点')
        }
        let data = obj.data
        // 缓存热点数据
        // if (this.hotspotsCache.id == obj.id) {
        //   data = this.hotspotsCache[obj.id]
        // } else {
        //   data = obj.data
        // }
        this.hotspotsCache[obj.id] = obj.data

        this.addHotspotComments(data.commentlist)
        this.addHotspotToScene(data.hotspotlist)
      },
      // 陀螺仪
      toggleGyro () {
        this.callScene('skin_switch_gyro();')
      },
      getGyroStatus () {
        return this.getSceneData('plugin[skin_gyro].enabled')
      },
      // 补地图片
      setBottomPic () {
        this.callScene("playscenesnow();")
      },
      // 切换化视角
      switchPerspective () {
        let viewType = this.getSceneData("scene[get(xml.scene)].isballview")
        console.log(viewType)
        // 第一次 并且 正常视角 不执行操作，否则小行星开场会有问题
        if (this.isFristCallViewType) {
          this.isFristCallViewType = false
          if (viewType != 0) {
            this.callScene(this.$CONFIG.perspectiveMenu[viewType].type)
          }
        } else {
          console.log('9------------')
          this.callScene(this.$CONFIG.perspectiveMenu[viewType].type)
        }
      },
      // 自动场景切换
      autoTurn () {
        // /aerialPhotography/52317
        // if (store.getters.aerialData && store.getters.aerialData.isonautoturn == 1) {
        //   this.setView("autorotate.enabled", "true")
        //   this.setView("autorotate.speed", store.getters.aerialData.autoturnspeed)
        // }
        // /panoview/51225
        if (store.getters.panoInfo && store.getters.panoInfo.isonautoturn == 1) {
          this.setView("autorotate.enabled", "true")
          this.setView("autorotate.speed", store.getters.panoInfo.autoturnspeed)
        }
      },
      stopTurn () {
        this.setView("autorotate.enabled", "false")
      },
      // 获取场景列表
      getScene () {
        let count = this.getSceneData("scene").count
        let scenePool = []
        for (let i = 0; i < count; i++) {
          scenePool.push(this.getSceneData("scene[" + i + "]"))
        }
        return scenePool
      },
      // 自动旋转
      autoRotate () {
        let speed = store.getters.panoInfo.autoturnspeed
        this.setView("autorotate.speed", speed)
        this.callScene("if(autorotate.enabled,autorotate.stop(),autorotate.start())")
      },
      // 自动旋转
      switchAutoRotate (bool) {
        let speed = store.getters.panoInfo.autoturnspeed
        this.setView("autorotate.speed", speed)
        this.callScene(`autorotate.${bool ? 'start' : 'stop'}()`)
      },
      // 设置krpano属性
      setScene (props, value) {
        this._krpano.set(props, value)
      },
      // call krpano
      callScene (str) {
        // console.log(str)
        this._krpano.call(str)
      },
      getView () {
        let hlookat = this.getSceneData("view.hlookat")
        let vlookat = this.getSceneData("view.vlookat")
        let fov = this.getSceneData("view.fov")

        return {
          hlookat: hlookat,
          vlookat: vlookat,
          fov: fov
        }
      },
      setView (name, val) {
        this.setScene(name, val)
      },
      toggleFull () {
        this._krpano.call('switch(fullscreen)')
      },
      // 监听PC VR模式退出事件
      vrPcExit () {
        this.$vgo.emit('vr:hide', true)
      },
      showVR () {
        // 微信 且 安卓系统
        // if (getDeviceType('wx') && getDeviceType('android')) {
        //   this.$vgo.emit('vrBugTip')
        // } else {
        this.callScene("webvr.enterVR();onshowVRhot();")
        this.$vgo.emit('vr:show', true)
        // }
      },
      // 隐藏VR
      hideVR () {
        this.callScene("webvr.exitVR();hidehotspot_enterVR();")
        this.$vgo.emit('vr:hide', true)
      },
      // 设置VR
      setupVR () {
        this.callScene("vr_setup()")
      },
      // 添加评论热点
      addHotspotComments (data) {
        this.hotspotCommentsData = data
        if (data && data.length) {
          data.map(item => {
            let hotspotName = "comment_" + item.comment_id;
            let avatarParentName = "comment_avatar_parent_" + item.comment_id;
            let avatarName = "comment_avatar_" + item.comment_id;
            let textName = "comment_text_" + item.comment_id;

            item.hotpoint = {
              name: hotspotName,
              id: item.comment_id,
              type: "image",
              url: $globalconfig.URLS.API + "/krpano/images/bg-comment.png",
              scale: 1,
              ath: item.ath,
              atv: item.atv,
              crop: '0|0|30|14',
              handcursor: false,
              is_comment: true
            }
            this._krpano.call("addhotspot(" + item.hotpoint.name + ");")
            for (let k in item.hotpoint) {
              let val = item.hotpoint[k]
              let key = k
              this._krpano.set("hotspot[" + item.hotpoint.name + "]." + key, val)
            }

            let hotspot = "hotspot[" + hotspotName + "]";

            item.layer = {
              name: avatarParentName,
              parent: hotspot,
              type: 'container',
              maskchildren: "true",
              align: "top",
              edge: "bottom",
              height: '30',
              width: '30',
              bgroundedge: '15'
            }
            this._krpano.call("addlayer(" + item.layer.name + ");")
            for (let j in item.layer) {
              let val = item.layer[j]
              let key = j
              this._krpano.set("layer[" + item.layer.name + "]." + key, val)
            }
            let avatarParent = "layer[" + avatarParentName + "]";

            item.authInfo = {
              name: avatarName,
              parent: avatarParent,
              url: item.avatar,
              align: "bottom",
              edge: "bottom",
              height: '30',
              width: '30',
              handcursor: false
            }
            this._krpano.call("addlayer(" + item.authInfo.name + ");")
            for (let m in item.authInfo) {
              let val = item.authInfo[m]
              let key = m
              this._krpano.set("layer[" + item.authInfo.name + "]." + key, val)
            }

            //如果是本人，添加删除功能
            let current_user_id = 0
            if ($AUTH.getCookie()) {
              current_user_id = this.userInfo ? this.userInfo.user_id : 0
            }
            if (item.user_id == current_user_id) {
              let delname = "del_" + item.comment_id
              this._krpano.call("addlayer(" + delname + ");")
              this._krpano.set("layer[" + delname + "].parent", hotspot)
              this._krpano.set("layer[" + delname + "].url", $globalconfig.URLS.API + 'krpano/images/x.png')
              this._krpano.set("layer[" + delname + "].align", "top")
              this._krpano.set("layer[" + delname + "].edge", "bottom")
              this._krpano.set("layer[" + delname + "].height", 30)
              this._krpano.set("layer[" + delname + "].width", 30)
              this._krpano.set("layer[" + delname + "].y", -30)
              this._krpano.set("layer[" + delname + "].type", "image")
              this._krpano.set("layer[" + delname + "].ondown", "set(delcommentid, " + item.comment_id + ");")
              this._krpano.set("layer[" + delname + "].onclick", this.onSayDel)
            }


            item.msg = {
              name: textName,
              parent: hotspot,
              url: $globalconfig.URLS.API + "/krpano/plugins/textfield.swf",
              html: item.contents,
              align: "top",
              edge: "left",
              autowidth: "true",
              x: '22',
              y: '-16',
              backgroundcolor: "0x000000",
              backgroundalpha: "0.4",
              padding: "5 8",
              roundedge: '4',
              css: " font-size: 12px;color: #FFFFFF;font-family:黑体;",
              handcursor: false
            }
            this._krpano.call("addlayer(" + item.msg.name + ");")
            for (let n in item.msg) {
              let val = item.msg[n]
              let key = n
              this._krpano.set("layer[" + item.msg.name + "]." + key, val)
            }
          })
        }
      },
      // 景点模板热点
      setHotspot12 (item) {
        const name = 'hotspot_' + item.hot_id
        this._krpano.call(`addhotspot(hotspot_${name})`)
        const obj = {
          name: `hotspot_${name}`,
          atv: item.atv, // 热点添加保存的位置
          ath: item.ath,
          diy_id: item.diy_id,
          type_id: item.type_id,
          style: 'hotspotstyle_normal', // 热点添加保存的style
          keep: false,
          enabled: true,
          bgcapture: true,
          ishotspot: true,
          handcursor: true,
          distorted: false,
          isshowmark: false,
          scalechildren: false,
          renderer: 'css3d',
          scale: isPc() ? item.scale : item.scaleapp,
          // width: "40",
          // height: "40",
          datastr: item.datastr,
          text: item.hot_name,
          tag_name: item.tag_name || '默认',
          url: $globalconfig.URLS.API + item.url,

          abank: item.abank,
          bgcolor: item.bgcolor,
          crop: item.crop,
          data_id: item.data_id,
          diy_src: item.diy_src,
          diydata: item.diydata,
          diytype: item.diytype,
          hot_id: item.hot_id,
          icon_id: item.icon_id,
          isstatic: item.isstatic,
          iswritephone: item.iswritephone,
          linkurl: item.linkurl,
          pano_id: item.pano_id,
          plugname: item.plugname,
          pointlist: item.pointlist,
          price: item.price,
          scaleapp: item.scaleapp,
          scene_id: item.scene_id,
          showtype: item.showtype,
          tag_id: item.tag_id,
          thumb: item.thumb,
          v: item.v,
          y: item.y,

          edge: 'bottom',
          zoom: false,
          autowidth: false,
          onclick: () => {
            const hot = this._krpano.get(`hotspot[hotspot_${name}]`)
            // console.log(hot)
            const { sprite } = hot
            if (!hot.isshowmark) {
              sprite.appendChild(this.tip.$el)
              sprite.style.backgroundImage = 'none'
              console.log(obj)
              this.tip.open(obj.text, obj.tag_name, obj.url)
              this.tip.set(obj)
              hot.isshowmark = true

              let filterArr = this.hotspotData.filter(hot => hot.hot_id != item.hot_id)
              // console.log(filterArr)
              filterArr.map(fil => {
                let otherHot = this._krpano.get(`hotspot[hotspot_hotspot_${fil.hot_id}]`)
                // console.log(otherHot)
                if (otherHot && otherHot.isshowmark) {
                  otherHot.sprite.style.backgroundImage = `url(${otherHot.url})`
                  otherHot.isshowmark = false
                }
              })

            } else {
              console.log('点击mark')
              // console.log(obj)
              handleHotspot(obj)
              // sprite.removeChild(this.tip.$el)
              // sprite.style.backgroundImage = `url(${obj.url})`
            }
          },
          onloaded: () => {
          },
        }
        for (const key in obj) {
          this._krpano.set(`hotspot[hotspot_${name}].${key}`, obj[key])
        }
      },
      // 其他模板热点，内嵌热点，场景标注，多边形热点
      setHotspot (item) {
        if (!item.bgcolor) {
          item.bgcolor = 'rgba(0,0,0,0.8)'
        }
        if (!item.showtype) {
          item.showtype = 'horizontal'
        }
        item.krname = {
          name: "hotspot_" + item.hot_id,
          capture: "false",
          ath: item.ath,
          atv: item.atv,
          diy_id: item.diy_id,
          type_id: item.type_id,
          style: item.style,
          onclick: () => {
            handleHotspot(item)
          },
          ondown: "set(tempname, hotspot_" + item.hot_id + ");",
          onup: this.onHotspotUp,
        }
        this._krpano.call("addhotspot(" + item.krname.name + ");")

        // 如果是竖排热点
        if (item.style == "hotspotstyle_vertical") {
          let txtlen = item.hot_name.length;
          let paddingtop = 110 + (Number(item.crop) - txtlen) * 10;
          item.krname = Object.assign(item.krname, {
            onloaded: "add_tooltip2(" + paddingtop + ");"
          });
        } else if (item.type_id == 19) {

        } else {
          // item.krname = Object.assign(item.krname, {
          //   onloaded: "add_tooltip('" + item.showtype + "','" + item.bgcolor + "');"
          // });
          // 竖排热点样式
          if (item.showtype == 'vertical') {
            const mSize = isPc() ? 12 : 9
            const mWidth = isPc() ? 14 : 9
            item.krname = Object.assign(item.krname, {
              onloaded: () => {
                let name = `tooltip_hotspot_${item.hot_id}`
                this._krpano.call(`addplugin(${name})`)
                this._krpano.set(`plugin[${name}].parent`, `hotspot[hotspot_${item.hot_id}]`)
                this._krpano.set(`plugin[${name}].type`, 'text')
                this._krpano.set(`plugin[${name}].align`, 'top');
                this._krpano.set(`plugin[${name}].edge`, 'bottom');
                this._krpano.set(`plugin[${name}].x`, 0);
                this._krpano.set(`plugin[${name}].y`, 0);
                this._krpano.set(`plugin[${name}].autowidth`, true);
                this._krpano.set(`plugin[${name}].autoheight`, true);
                this._krpano.set(`plugin[${name}].vcenter`, true);
                this._krpano.set(`plugin[${name}].background`, false);
                this._krpano.set(`plugin[${name}].roundedge`, 4);
                this._krpano.set(`plugin[${name}].backgroundalpha`, 1);
                this._krpano.set(`plugin[${name}].border`, false);
                this._krpano.set(`plugin[${name}].glow`, 0);
                this._krpano.set(`plugin[${name}].glowcolor`, 0xFFFFFF);
                this._krpano.set(`plugin[${name}].html`, item.hot_name);
                this._krpano.set(`plugin[${name}].visible`, true);
                this._krpano.set(`plugin[${name}].showtype`, item.showtype);
                this._krpano.set(`plugin[${name}].css`, `color:#FFFFFF;font-family: MicrosoftYahei;font-size:${mSize}px;width:${mWidth}px;text-align:center;word-wrap:break-word;white-space: pre-wrap;padding:5px 3px;background-color:${item.bgcolor};margin:0px 0px 0px 0px;border-radius:5px;`);
              },
            });
          } else {
            item.krname = Object.assign(item.krname, {
              onloaded: "add_tooltip('" + item.showtype + "','" + item.bgcolor + "');"
            });
          }
        }

        // 内置
        if (item.diy_id == 0) {
          // 航拍场景热点
          if (item.type_id == 19) {
            // true不触发onover,onout事件
            // this._krpano.call("add_tooltip('"+ item.showtype +"','"+ item.bgcolor +"');")
            item.biaoji = false
            if (!isJSON(item.datastr)) return
            let datastrobj = JSON.parse(item.datastr)
            console.log('19-------------------------')
            datastrobj.full_default_icon = $globalconfig.URLS.PLUGIN_API + datastrobj.default_icon
            datastrobj.full_chosen_icon = $globalconfig.URLS.PLUGIN_API + datastrobj.chosen_icon
            // item.data_id = ''
            item.krname = Object.assign({}, item.krname, {
              url: datastrobj.full_default_icon,
              linkedscene: null,
              text: "" + item.hot_name + "",
              scale: item.scale,
              edge: "bottom",
              width: "38",
              y: 0,
              // data_id: `id=${datastrobj.scene_id},show`,
              onloaded: () => {
                let name = `tooltip_hotspot_${item.hot_id}`
                this._krpano.call(`addplugin(${name})`)
                this._krpano.set(`plugin[${name}].parent`, `hotspot[hotspot_${item.hot_id}]`)
                this._krpano.set(`plugin[${name}].type`, 'text')
                this._krpano.set(`plugin[${name}].align`, 'top');
                this._krpano.set(`plugin[${name}].edge`, 'bottom');
                this._krpano.set(`plugin[${name}].x`, 0);
                this._krpano.set(`plugin[${name}].y`, 0);
                this._krpano.set(`plugin[${name}].autowidth`, true);
                this._krpano.set(`plugin[${name}].autoheight`, true);
                this._krpano.set(`plugin[${name}].vcenter`, true);
                this._krpano.set(`plugin[${name}].background`, false);
                this._krpano.set(`plugin[${name}].roundedge`, 4);
                this._krpano.set(`plugin[${name}].backgroundalpha`, 0.5);
                this._krpano.set(`plugin[${name}].border`, false);
                this._krpano.set(`plugin[${name}].glow`, 0);
                this._krpano.set(`plugin[${name}].glowcolor`, 0xFFFFFF);
                this._krpano.set(`plugin[${name}].html`, item.hot_name);
                this._krpano.set(`plugin[${name}].visible`, true);
                this._krpano.set(`plugin[${name}].showtype`, item.showtype);
                this._krpano.set(`plugin[${name}].css`, 'color:#FFFFFF;font-family: MicrosoftYahei;font-size:13px;width:13px;text-align:center;word-wrap:break-word;white-space: pre-wrap;padding:5px 3px;background-color: rgba(0,0,0,0.5);margin:0px 0px 0px 0px;border-top-right-radius:8px;border-top-left-radius:8px;');
              },
              onover: _ => {
                if (item.biaoji) { return }
                // console.log('onover-----------')
                const tool = this._krpano.get(`plugin[tooltip_${"hotspot_" + item.hot_id}]`)
                // console.log(tool.sprite.parentNode)
                const el = tool.sprite.querySelector('td > div')
                // console.log(tool)
                if (el) {
                  tool.sprite.parentNode.style['background-image'] = `url(${datastrobj.full_chosen_icon})`
                  el.style['background-color'] = 'rgba(221,221,221,0.5)'
                  el.style.color = '#333'
                }
              },
              onout: _ => {
                if (item.biaoji) { return }
                // console.log('onout-----------')
                const tool = this._krpano.get(`plugin[tooltip_${"hotspot_" + item.hot_id}]`)
                if (!tool) { return }
                const el = tool.sprite.querySelector('td > div')
                if (el) {
                  tool.sprite.parentNode.style['background-image'] = `url(${datastrobj.full_default_icon})`
                  el.style['background-color'] = 'rgba(0,0,0,0.5)'
                  el.style.color = '#fff'
                }
              },
            });
            // console.log(item)
          }
          if (item.type_id == 16) { // 标注
            let labelColor = Number(item.datastr.split('|')[1])

            item.krname = Object.assign(item.krname, {
              url: $globalconfig.URLS.API + `krpano/hoticon/${labelColor == 1 ? 'whitetag' : 'blacktag'}.png`,
              linkedscene: null,
              text: "" + item.hot_name + "",
              handcursor: "false",
              scale: item.scale,
              width: "20",
              // width: `${labelColor == 1? 200: 20}`,
              edge: "bottom",
              //zoom: "true",
              y: 0
            });
          }
          if (item.type_id == 14) { // 内嵌文字
            let dataObj = this.formatDataStr(item.datastr)

            item.krname = Object.assign(item.krname, {
              id: item.hot_id,
              url: $globalconfig.URLS.API + "krpano/edit/text_img.aspx?text=" + encodeURIComponent(dataObj.title) + "&color=" + dataObj.color + "&size=" + dataObj.size,
              type: "image",
              rx: dataObj.rx || '0',
              ry: dataObj.ry || '0',
              rotate: dataObj.rotate || '0',
              scale: dataObj.scale || '0.5',
              keep: "false",
              enabled: "true",
              scale: item.scale,
              edge: "bottom",
              bgcapture: true,
              ishotspot: true,
              handcursor: true,
              distorted: true,
              onloaded: ""
            })
          }
          if (item.type_id == 9) { // 视频
            pauseAllAudio()
            let dataObj = this.formatDataStr(item.datastr)
            item.krname = Object.assign(item.krname, {
              url: $globalconfig.URLS.API + "krpano/plugins/videoplayer.js",
              videourl: (dataObj.url.indexOf('http') != -1 ? "" : $globalconfig.URLS.API) + dataObj.url,
              posterurl: isIos() ? require('@/assets/img/ship.jpg') : '',
              distorted: true,
              width: dataObj.width,
              height: dataObj.height,
              rx: dataObj.rx || '0',
              ry: dataObj.ry || '0',
              rotate: dataObj.rotate || '0',
              scale: dataObj.scale || '0.5',
              edge: "center",
              loop: true,
              preload: true,
              autoplay: true,
              // autoalpha: true,
              pausedonstart: false, // true 暂停 !!$globalconfig.pausedonstart
              onclick: () => {
                const name = "hotspot_" + item.hot_id
                const krObj = this._krpano.get(`hotspot[${name}]`)
                if (krObj && krObj.videoDOM) {
                  if (krObj.videoDOM.paused) {
                    pauseAllAudio()
                  } else {
                    replaySceneOrBgMusic()
                  }
                  krObj.togglepause()
                }
              },
              onloaded: '',
              // onloaded: () => {
              //   let name = "hotspot_" + item.hot_id
              //   const krObj = this._krpano.get(`hotspot[${name}]`)
              //   console.log(krObj)
              //   console.log(krObj.videoDOM)
              //   if (krObj && krObj.videoDOM) {
              //     krObj.videoDOM.style['min-width'] = '100px'
              //     krObj.videoDOM.style['min-height'] = '100px'
              //     krObj.videoDOM.style['background-image'] = 'url(static/images/zt36.png)'
              //     var img = document.createElement('img')
              //     img.src = 'static/images/zt36.png'
              //     img.style.position = 'absolute'
              //     img.style.zIndex = '99999999999999'
              //     img.style.width = '70px'
              //     img.style.height = '70px'
              //     console.log(img)
              //     krObj.videoDOM.appendChild(img)
              //   }
              // },
              muted: true, // !isPc()
              onvideoready: () => {
                if ($globalconfig.pausedonstart) return
                let name = "hotspot_" + item.hot_id
                let isPlay = false
                const krObj = this._krpano.get(`hotspot[${name}]`)
                if (!krObj) return false

                $VM.$vgo.$on('wxjssdkinit', () => {
                  // alert('124--------')
                  if (krObj.videoDOM && krObj.videoDOM.paused) {
                    // alert('125--------')
                    krObj.togglepause()
                    pauseAllAudio
                  }
                })
                const touchFunc = () => {
                  isPlay = true
                  this._krpano.set(`hotspot[${name}].muted`, false)
                  if (krObj.videoDOM.paused) {
                    krObj.togglepause()
                    setTimeout(() => {
                      pauseAllAudio()
                    }, 100)
                  }
                  window.removeEventListener('touchstart', touchFunc, false)
                }
                if (!isPlay) {
                  window.addEventListener('touchstart', touchFunc, false)
                }
              },
              onvideoplay: () => {
                setTimeout(() => {
                  let name = "hotspot_" + item.hot_id
                  this._krpano.set(`hotspot[${name}].muted`, false)
                }, 100);
              },
            })
          }
          if (item.type_id == 7) {
            let dataObj = this.formatDataStr(item.datastr)

            item.krname = Object.assign(item.krname, {
              distorted: "true",
              url: $globalconfig.URLS.API + dataObj.url,
            })
            if (dataObj.width) {
              item.krname = Object.assign(item.krname, {
                text: "" + item.hot_name + "",
                width: dataObj.width,
                height: dataObj.height,
                rx: dataObj.rx,
                ry: dataObj.ry,
                rotate: dataObj.rotate,
                scale: dataObj.scale || '0.5',
                onclick: '',
                onloaded: "add_tooltip('" + item.showtype + "','" + item.bgcolor + "');"
              })
            }
          }
          //vr模式内嵌入元素处理
          let vrinnername = "vrhotspot_" + item.hot_id
          this._krpano.call("addhotspot(" + vrinnername + ");")
          this._krpano.set("hotspot[" + vrinnername + "].isvr", 'true')
          for (let k in item.krname) {
            let val = item.krname[k]
            let key = k
            this._krpano.set("hotspot[" + vrinnername + "]." + key, val)
          }
          if (item.type_id != 9) {//去除VR模式下的事件
            this._krpano.set("hotspot[" + vrinnername + "].onclick", this.onHotspotOver)
          }

        } else {
          let hasName = (item.hot_name == "") ? "" : "add_tooltip('" + item.showtype + "','" + item.bgcolor + "');"
          let onLoadedVal = 'hotspot_animate();' + hasName
          console.log(onLoadedVal)

          item.krname = Object.assign({}, item.krname, {
            url: $globalconfig.URLS.API + item.diy_src,
            linkedscene: item.datastr,
            text: "" + item.hot_name + "",
            scale: isPc() ? item.scale : item.scaleapp,
            edge: "bottom",
            autowidth: "true",
            y: 0,
            abank: item.abank,
            plugname: item.plugname,
            datastr: item.datastr,
            linkurl: item.linkurl,
            price: item.price,

          })
          if (item.type_id != 13 &&
            item.type_id != 15 &&
            item.style &&
            item.style != "hotspotstyle_normal"
            && item.style != "hotspotstyle_vertical"
          ) {
            let frame = this.formatFrame(item.style)
            let framearr = item.crop.split('|')

            item.krname = Object.assign(item.krname, {
              enabled: "true",
              crop: item.crop,
              framewidth: framearr[2],
              frameheight: framearr[3],
              frame: 0,
              lastframe: frame,
              onloaded: onLoadedVal,
            })
          }
          if (item.type_id == 13 || item.type_id == 15) { //gif
            let dataObj = this.formatDataStr(item.datastr)

            item.krname = Object.assign({}, item.krname, {
              distorted: item.type_id == 13 ? "true" : "false",
              url: $globalconfig.URLS.API + dataObj.url,
              type: "image",
              keep: "false",
              enabled: "true",
              edge: "bottom",
              bgcapture: true,
              ishotspot: true,
              handcursor: true,
            })

            if (dataObj.width) {
              item.krname = Object.assign({}, item.krname, {
                width: dataObj.width,
                height: dataObj.height,
                rx: dataObj.rx,
                ry: dataObj.ry,
                rotate: dataObj.rotate,
                scale: dataObj.scale || '0.5'
              })
            }

            if (item.type_id == 15) {
              this.$vgo.once('noticetip:show', { title: '欢迎参与找红包', desc: '场景内有大量现金红包随机散落在场景内，赶紧去找，晚了就没有啦！' })

              if (item.abank == 2) {
                let aa = (Math.random() > 0.5) ? -1 : 1;
                let bb = (Math.random() > 0.5) ? -1 : 1;
                let atv = Math.random() * 90 * aa
                let ath = Math.random() * 180 * bb
                item.krname = Object.assign(item.krname, {
                  atv: Number(atv).toFixed(2),
                  ath: Number(ath).toFixed(2),
                })
              }
            }

            if (item.style != "hotspotstyle_normal" && item.style != "hotspotstyle_diynormal") {
              let frame = this.formatFrame(item.style)

              let framearr = item.crop.split('|')
              item.krname = Object.assign({}, item.krname, {
                enabled: "true",
                crop: item.crop,
                framewidth: framearr[2],
                frameheight: framearr[3],
                frame: 0,
                lastframe: frame,
                onloaded: onLoadedVal
              })
            }
          }
        }

        //vr模式热点
        if (item.type_id == 1) {
          let vrkrname = "vrhotspot_" + item.hot_id
          this._krpano.call("addhotspot(" + vrkrname + ");")
          this._krpano.set("hotspot[" + vrkrname + "].isvr", 'true')
          this._krpano.set("hotspot[" + vrkrname + "].id", item.hot_id)
          this._krpano.set("hotspot[" + vrkrname + "].keep", 'false')
          this._krpano.set("hotspot[" + vrkrname + "].distorted", 'true')
          this._krpano.set("hotspot[" + vrkrname + "].depth", '1000')
          this._krpano.set("hotspot[" + vrkrname + "].zorder", '2')
          this._krpano.set("hotspot[" + vrkrname + "].visible", 'false')
          this._krpano.set("hotspot[" + vrkrname + "].atv", item.krname.atv)
          this._krpano.set("hotspot[" + vrkrname + "].ath", item.krname.ath)
          this._krpano.set("hotspot[" + vrkrname + "].type", 'image')
          this._krpano.set("hotspot[" + vrkrname + "].onclick", this.onHotspotClick)
          this._krpano.set("hotspot[" + vrkrname + "].onover", "set(tempname, " + vrkrname + ");")
          this._krpano.set("hotspot[" + vrkrname + "].url", item.krname.url)
          this._krpano.set("hotspot[" + vrkrname + "].scale", item.krname.scale)

          if (item.style == "hotspotstyle_vertical") {
            item.style = "hotspotstyle_normal"
          }
          this._krpano.set("hotspot[" + vrkrname + "].style", item.krname.style)

          if (item.style != "hotspotstyle_normal" && item.style != "hotspotstyle_diynormal") {
            let frame = item.style
            if (frame && frame.indexOf('x') == -1) {
              frame = frame.split('_')[1].replace('gif', '') //兼容老的热点素材数据
            }
            let framearr = item.crop.split('|')
            this._krpano.set("hotspot[" + vrkrname + "].enabled", 'true')
            this._krpano.set("hotspot[" + vrkrname + "].crop", item.crop)
            this._krpano.set("hotspot[" + vrkrname + "].framewidth", framearr[2])
            this._krpano.set("hotspot[" + vrkrname + "].frameheight", framearr[3])
            this._krpano.set("hotspot[" + vrkrname + "].frame", "0")
            this._krpano.set("hotspot[" + vrkrname + "].lastframe", frame)
            this._krpano.set("hotspot[" + vrkrname + "].onloaded", "hotspot_animate();")
          }
          if (this._krpano.get("webvr.isenabled")) {
            this._krpano.set("hotspot[" + vrkrname + "].visible", 'true')
          }
        }

        if (item.pointlist && item.pointlist.length) {
          this._krpano.set("hotspot[" + item.krname.name + "].style", 'shapespot')
          this._krpano.set("hotspot[" + item.krname.name + "].scale", '1.0')
          this._krpano.set("hotspot[" + item.krname.name + "].onclick", this.onHotspotClick)
          this._krpano.set("hotspot[" + item.krname.name + "].ondown", "set(tempname, hotspot_" + item.hot_id + ");")
          this._krpano.set("hotspot[" + item.krname.name + "].onup", this.onHotspotUp)
          this._krpano.set("hotspot[" + item.krname.name + "].borderwidth", "0.0")
          this._krpano.set("hotspot[" + item.krname.name + "].alpha", "0.8")
          this._krpano.set("hotspot[" + item.krname.name + "].fillcolor", "0xffffff")
          this._krpano.set("hotspot[" + item.krname.name + "].animation", "tween(alpha, calc(1.1 - alpha), 3.0, linear, animation());")
          this._krpano.set("hotspot[" + item.krname.name + "].onloaded", "animation();")

          for (let pointindx = 0; pointindx < item.pointlist.length; pointindx++) {
            let point = item.pointlist[pointindx]
            this._krpano.set("hotspot[" + item.krname.name + "].point[" + pointindx + "].ath", point.ath)
            this._krpano.set("hotspot[" + item.krname.name + "].point[" + pointindx + "].atv", point.atv)
          }
        } else {
          for (let k in item.krname) {
            let val = item.krname[k]
            let key = k
            this._krpano.set("hotspot[" + item.krname.name + "]." + key, val)
          }
          item.krname = null
        }
      },
      // 添加热点
      addHotspotToScene (data) {
        this.hotspotData = data
        if (data && data.length) {
          if (this.getTemp12) {
            // 景点模板热点样式
            data.map(item => {
              // 处理音乐重叠
              if (item.diy_id == 0 && item.type_id == 9 && !isIos()) {
                pauseAllAudio()
              }

              if (item.diy_id == 0 || item.diy_id == -100) {
                this.setHotspot(item)
              } else {
                this.setHotspot12(item)
              }
            })
          } else {
            data.map(item => {
              // 处理音乐重叠
              if (item.diy_id == 0 && item.type_id == 9 && !isIos()) {
                pauseAllAudio()
              }
              this.setHotspot(item)
            })
          }
        }
      },
      formatFrame (str) {
        if (!str) return
        let frame = ''
        frame = str.split('_')[1]
        if (!~frame.indexOf('x')) {
          frame = frame.replace('gif', '')
        } else {
          frame = frame.split('x')[0]
        }

        return frame
      },
      // 格式热点数据
      formatDataStr (str) {
        let dataArr = str.split('|')
        let obj = {}
        if (dataArr.length > 2) {
          obj.title = decodeURIComponent(dataArr[0])
          obj.url = dataArr[1]
          obj.width = dataArr[2]
          obj.height = dataArr[3]
          obj.rx = dataArr[4]
          obj.ry = dataArr[5]
          obj.rotate = dataArr[6]
          obj.scale = dataArr[7]
          obj.size = dataArr[8]
          obj.color = dataArr[9]
          return obj
        } else { //兼容老版本
          obj.url = dataArr[0]
          return obj
        }
      },
      // 热点点击
      onHotspotClick () {
        let hotId = this.getSceneData("tempname").split('_')[1]
        this.hotspotData.map(item => {
          if (item.hot_id == hotId) {
            handleHotspot(item)
          }
        })
      },
      onHotspotOver () { },
      onHotspotUp () {
        console.log(this.getSayLocation())
      },
      //点说一说弹出可拖动位置的图
      onShowSay () {
        let hotspotName = "temp_comment";
        // let avatarParentName = "temp_avatar_parent_" + item.comment_id;
        // let avatarName = "temp_avatar_" + item.comment_id;
        // let textName = "temp_text_" + item.comment_id;
        let location = this.getView()
        let hotpoint = {
          name: hotspotName,
          type: "image",
          url: "/static/images/drag.png",
          scale: 0.8,
          ath: location.hlookat,
          atv: location.vlookat,
          edge: "bottom",
          handcursor: true,
          ondown: "draghotspot();",
          onup: this.onHotspotUp,
        }
        this._krpano.call("addhotspot(" + hotspotName + ");")
        for (let k in hotpoint) {
          let val = hotpoint[k]
          let key = k
          this._krpano.set("hotspot[" + hotspotName + "]." + key, val)
        }
      },

      removeDragSayModel () {
        this._krpano.call("removehotspot(temp_comment);")
      },
      getSayLocation () {
        return {
          ath: Number(this.getSceneData("hotspot[temp_comment].ath")).toFixed(2),
          atv: Number(this.getSceneData("hotspot[temp_comment].atv")).toFixed(2),
        }
      },
      onSayDel () {
        let id = this._krpano.get("delcommentid")
        $API('delSay', [id]).then(res => {
          this._krpano.call("removehotspot(comment_" + id + ");")
          $VM.$vgo.tip('删除说一说成功！', 'warning')
        })

      },

    }
  })
  Vue.prototype.$krp = krviewPlugin
}

export default install
